<?php
	App::import('Vendor', 'languages/en_lang');
	App::import('Vendor', 'functions/custom_functions');
	require_once getcwd().'/../vendors/Authorizenet/config.php';
	App::import('Sanitize');
	
	
class AppController extends Controller {
	var $helpers = array('Form','Javascript', 'Session','Facebook.Facebook' => array('locale' => 'en_US'),'Html','Form','Ajax','Text');
	var $uses = array('User','Forgot','Brand','Category','Menu','MenuItem','Page','Product','ProductConsType','ProductProsType','ProductReview','Rating','Shipping','ShippingSp','Specification', 'AttrGroup', 'Attribute', 'Option','StockStatus','Country','Coupon', 'Gift', 'OptionValue', 
	'Department', 'Seller', 'Country', 'Address', 'ProductCondition', 'MasterProduct', 'SellerPage', 'Wishlist','WishlistProduct','UpsShipping','FedexShipping','State','FlateRate','Message','MessageSubject','Paypal','Order','OrderItem','SellerFeedback','Helpfull');
	
	var $components = array('Session','Auth', 'Cookie', 'RequestHandler','Brownie.panel','Facebook.Connect', 'Email');
	
	
	
/* Function beforeFilter*/
		function beforeFilter()
		{
			$fb_id = $this->Connect->user('id');
			$this->Set('fb_id', $fb_id);
			$website_image_url = Configure::read('Website.image_url');
			$this->Set('website_image_url',$website_image_url);
			$website_url = Configure::read('Website.url');
			$this->Set('website_url',$website_url);
			$METHOD_TO_USE = "AIM";
			$this->Set('METHOD_TO_USE',$METHOD_TO_USE);
			
			/*
			* Cart Total Items
			*/
				$count_cart = $this->Session->read('cart.product_id');
				if(isset($count_cart) and ($count_cart))
					{
						$count_cart = $count_cart; 
						$count_cart  = count($count_cart);
					}
				else
					{
						$count_cart = "0";
					}
			$this->Set('count_cart', $count_cart); 
			/*
			* End Cart Total Items
			*/
            			
			/*
				* Top Category Search
			*/
					$parent_cats = $this->_list_parent_categories(); 
					if(isset($parent_cats) and ($parent_cats))
					$total = count($parent_cats);
					$parent_cats[0] = "All Categories";
					ksort($parent_cats);
					$this->Set('Seach_categories', $parent_cats);
					
			/*
				* End Top Category Search
			*/
			/*Menu Footer*/
				$menu_list = $this->Menu->find('all', array('fields'=>'Menu.id'));
				if(isset($menu_list) and ($menu_list))
					{
						foreach($menu_list as $menu)
							{
								$menus_list = $this->load_menu($menu['Menu']['id']);
								$footer_menu[] = $menus_list;
							}
							
							if(isset($footer_menu) and ($footer_menu))
								{
									$this->Set('footer_menu', $footer_menu);
								}
					}

			/* Menu Footer Endss*/
			
			$current_action = $this->action;
			$current_controller = $this->name;
			if($current_controller == 'Setups'){
				$this->layout='admin';
				if(isset($current_action) and ($current_action=='admin_login'))
					{
						return true;
					}
				else if(isset($current_action) and ($current_action=='admin_login'))
					{
						return true;
					}
				else
					{
						$this->__IsAdminAuthorised();
					}
				
			}
			else if($current_controller == 'Sellers'){
				$this->layout='Seller';
				if(isset($current_action) and ($current_action=='login'))
					{
						return true;
					}
				else if(isset($current_action) and ($current_action=='logout'))
					{
						return true;
					}
				else if(isset($current_action) and ($current_action=='confirmed_need'))
					{
						return true;
					}
				else if(isset($current_action) and ($current_action=='sellerjoin' or $current_action=='store' or $current_action=='update_inventory'))
					{
						return true;
					}
				else if(isset($current_action) and ($current_action=='get_brand_lock'))
					{
						return true;
					}	
				else if(isset($current_action) and ($current_action=='ajax_login'))
					{
						return true;
					}	
					
				else if(isset($current_action) and ($current_action=='account_info'))
					{
						$is_seller = $this->Auth->User("is_seller");
						 if((isset($is_seller) and ($is_seller=='1')))
							 {
								 return true; 
							 }
						 else
							 {
								$this->redirect($this->Auth->logout());
							 }
					}
					else
					{
						//echo "else";
						$this->__IsSellerAuthorised();
					}
				
			}
		}
		
		function _product_specification($product_id)
		{
									$specifications_attributes = $this->Specification->find('all', array(
							'conditions' => 'Specification.product_id="' . $product_id . '"',
							'fields'=>'DISTINCT Specification.attr_id'
						));
						//pr( $specifications_attributes );
					   // exit;
						if(isset( $specifications_attributes ) and ( $specifications_attributes ))
							{
								
								foreach($specifications_attributes  as $specifications_attribute)
									{
											$Attribute_GP_ID = $this->Attribute->find('first', array(
																'conditions' => 'Attribute.id="' . $specifications_attribute['Specification']['attr_id'] . '"
																',
																'fields'=>'Attribute.attr_gp_id'
																));
											if(isset($Attribute_GP_ID) and ($Attribute_GP_ID))
												{
													$Gp_atr[] = 	$Attribute_GP_ID['Attribute']['attr_gp_id']; 
												}
									}
									$Gp_atr = array_unique($Gp_atr);
							}
							
						
						
							
						if(isset($Gp_atr) and ($Gp_atr))
							{
								$v =0;
								foreach($Gp_atr as $Gp_at)
									{
										$Gp_atr_1[$v] = $Gp_at;
										$v++; 
									}
								$x=0;
								foreach($Gp_atr_1 as $Gp_ID)
								{
									$GRP_ATTR = $this->AttrGroup->findById($Gp_ID);
									$Attributes = $this->Attribute->find('all', array(
																	'conditions' => 'Attribute.attr_gp_id="' .$Gp_ID. '"',
																	'fields'=>'Attribute.id' 
																	));
										
										$o=0;
										foreach($Attributes as $Attribute_id)
											{
												$specifications = $this->Specification->find('all', array(
												'conditions' => 'Specification.attr_id="' . $Attribute_id['Attribute']['id'] . '"',
												));
												$specifications = array_unique($specifications);
												if(isset($specifications) and ($specifications)):
												
												foreach($specifications as $specification){
													$xc =0;
													$attribute_key   = $this->__get_attr_name($specification['Specification']['attr_id']);
													$specifications[$xc]['Specification']['key'] = $attribute_key['Attribute']['name'];
													$xc++;
												}
												endif;
												unset($Attributes[$o]['Attribute']); 
												$Attributes[$o]['Specifications'] = $specifications; 
												$o++;
											}
									$Gp_atr_1[$x]=$GRP_ATTR; 
									$Gp_atr_1[$x]['AttrGroup']['Attributes'] = $Attributes ; 
									$x++;
								}
								//pr($Gp_atr_1);
								//exit;
							return $Gp_atr_1; 
							}

		}
		
		function __validateLogin($data)
			{  
				$this->User->recursive = 0; 
				$enc_password = md5($data['passwd']);
				$user = $this->User->find('first',
									 array(
												'conditions'=>array(
																	"User.email" => $data['email'],
																	'User.passwd' => $enc_password ,
																	'User.is_verified' => '1'
																	),
												'fields' =>array(
																	'User.* '
																	)
																	
											)
										);
					if(empty($user) == false)
					{
						unset($user['passwd']);
						return $user['User'];
					}
					else
					{
						return false;
					}
			}
		
	/* Function to check login user is valid Status.*/

		function __validateLoginStatus()
			{
				if($this->Session->check('User') == false)
					{
						$this->redirect('../users/login');
						$this->Session->setFlash('The URL you\'ve followed requires you login.');
					}
				else
					{
						return true;
					}
			}
			
		function __generateKey($model="")
			{
				$time = time();
				$rand = rand();
				$time = $time + $rand;
				$hashkey = md5($time);
				$hashkey = substr($hashkey, 8, 16);
				$hashkeycheck = $this->$model->find('all', array('conditions' => ''.$model.'.hash = "'.$hashkey.'"'));
				if(sizeof($hashkeycheck))
					{
						$this->__generateKey();	
					}
				else
					{
						return $hashkey;
					}
			}
		
		function ___randLetter()
			{
				$int = rand(0,51);
				$a_z = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
				$rand_letter = $a_z[''.$int.''];
				return $rand_letter;
			}
			
			
		function __generateWisn($model="")
			{
				$time = time();
				$rand = rand();
				//$letter = $this->___randLetter();
				$time = $time + $rand;
				$hashkey = md5($time);
				$hashkey = substr($hashkey, 8, 16);
				$hashkey = $hashkey;
				$hashkey = strtoupper($hashkey);
				$hashkeycheck = $this->$model->find('all', array('conditions' => ''.$model.'.wisn = "'.$hashkey.'"'));
				if(sizeof($hashkeycheck))
					{
						$this->__generateWisn($model="");	
					}
				else
					{
						return $hashkey;
					}
			}
			
			
		function __generateToken($model="", $field ="")
			{
				$time = time();
				$rand = rand();
				$time = $time + $rand;
				$hashkey = md5($time);
				$hashkey = substr($hashkey, 8, 16);
				$hashkeycheck = $this->$model->find('all', array('conditions' => ''.$model.'.'.$field.' = "'.$hashkey.'"'));
				if(sizeof($hashkeycheck))
					{
						$this->__generateToken();	
					}
				else
					{
						return strtoupper($hashkey);
					}
			}
			
		function __rand_key($key)
			{
				$hashkey = md5($key);
				$hashkey = substr($hashkey, 8, 16);
				return $hashkey;
			}
	/* Function to Send E-Mail.*/
	
 function __send_mail($mail_persons_list, $mail_subject, $mail_message, $mail_from_email = "", $mail_from_name = "", $attch="")
		{
			if( isset($attch) and ( $attch))
			{
				 $attch=$attch;
			}else
			{
				$attch = "http://wondere.com/img/logo.png";
			}
			 
			App::import('Vendor', 'swift_mailer/lib/swift_required');
			//App::import('Vendors', 'WellNamed', array('file' => 'services'.DS.'well.named.php'));
			$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")
					  ->setUsername('vineetpnf@gmail.com')
					  ->setPassword('vineet07vermapnf')
						  ;

			$mailer = Swift_Mailer::newInstance($transport);
			if(!$mail_from_email)
				{
					//Take mail from from email config
					$mail_from_email = Configure::read('Website.from_email');
				}
			if(!$mail_from_name)
				{
					//Take mail from from name config
					$mail_from_name = Configure::read('Website.from_name');		
				}
			$message = Swift_Message::newInstance(''.$mail_subject.'')
			->setFrom(array(''.$mail_from_email.'' => ''.$mail_from_name.''))
			->setTo($mail_persons_list)
			->setBody(''.$mail_message.'', 'text/html')
			->addPart(''.$mail_message.'', 'text/plain')
			->attach(Swift_Attachment::fromPath($attch))
			;
			//pr($message);
			//exit;
			//Send the message
			$result = $mailer->send($message);
		}
		
		
	function __get_product_min_price($product_id)
		{
			if(isset($product_id) and ($product_id))
			{
				$top_5_sellers_95_percentage_rating = $this->_get_top_5_sellers();
				if(isset($top_5_sellers_95_percentage_rating ) and ($top_5_sellers_95_percentage_rating )):
					foreach($top_5_sellers_95_percentage_rating  as $top_5_seller)
						{
							$top_sellers[] = $top_5_seller['seller_feedbacks']['seller_id']; 
						}  
				endif;
				
				
				$todayDate = date("Y-m-d g:i a");// current date
				$currentTime = time($todayDate); 
				$timeAfterOneHour = $currentTime+60*60;
				$OneHourTimeStamp = $this->Session->read('OneHourTimeStamp');
				if(isset($OneHourTimeStamp) and ($OneHourTimeStamp))
					{
						if($currentTime>$OneHourTimeStamp)
							{
								$session_seller_id =$this->Session->read('MiniMumTopSellerID');
								shuffle($top_sellers);
								if($top_sellers[0]==$session_seller_id)
									{
										$seller_id = $top_sellers[1]; 
									}
								else
									{
										$seller_id = $top_sellers[0]; 
									}
								$this->Session->write('MiniMumTopSellerID', $seller_id); 
								$this->Session->write('OneHourTimeStamp', $timeAfterOneHour); 
							}
						else
							{
								$seller_id =$this->Session->read('MiniMumTopSellerID');
							}
						
					}
				else
					{
						shuffle($top_sellers);
						$seller_id  = $top_sellers[0]; 
						$this->Session->write('MiniMumTopSellerID', $seller_id); 
						$this->Session->write('OneHourTimeStamp', $timeAfterOneHour); 
					}
					
				$min_price_product = $this->MasterProduct->query("Select min(price) as Price from master_products where product_id=".$product_id."
				and seller_id=".$seller_id." ");
					if(isset($min_price_product) and ($min_price_product))
						{
							$master_row = $this->MasterProduct->find('all', 
							array('conditions'=>'MasterProduct.price="'.$min_price_product[0][0]['Price'].'"
							 and product_id="'.$product_id.'" and seller_id="'.$seller_id.'"', 
								  'order'=>'MasterProduct.created Desc', 'limit'=>'1'));
							if(isset($master_row[0]) and ($master_row[0]))
								{
									return $master_row[0]['MasterProduct']; 	
								}
						}
						else
						{
							return false;
						}
			}
			else
				{
					return false;
				}
		}
	
	function __getPaid_product_min_price($product_id="", $seller_id="")
		{
			if(isset($product_id) and ($product_id) and isset($seller_id) and ($seller_id))
				{
					$master_row = $this->MasterProduct->find('all', 
					array('conditions'=>'MasterProduct.product_id="'.$product_id.'" and MasterProduct.seller_id="'.$seller_id.'"', 
						  'order'=>'MasterProduct.created Desc',
						  'limit'=>'1'
					));
								if(isset($master_row[0]) and ($master_row[0]))
									{
										return $master_row[0]['MasterProduct']; 	
									}
				}
			else
				{
					return false;
				}
		}
	
	
		
	function __get_product_condition_price($price, $product_id)
		{
			if(isset($product_id) and ($product_id))
				{
				
					$min_price_product = $this->MasterProduct->query("Select min(price) as Price from master_products where product_id=".$product_id."");
					if($price=="less_100")
					{
						if($min_price_product[0][0]['Price']<100)
						{
							$min_price_product[0][0]['Price'] = $min_price_product[0][0]['Price'];
						}
						else
						{
							$min_price_product[0][0]['Price']  ="";
						}
						//$Master_conditions ="MasterProduct.price=<'100'";
					}
					elseif($price=="over_5000")
					{
						if($min_price_product[0][0]['Price']>5000)
							{
								$min_price_product[0][0]['Price'] =$min_price_product[0][0]['Price'];
							}
						else
							{
								$min_price_product[0][0]['Price']  ="";
							}
					}
					else
					{
						$explode = explode('_', $price);
						if(($min_price_product[0][0]['Price']>$explode[0]) and ($min_price_product[0][0]['Price']<$explode[1]))
							{
								$min_price_product[0][0]['Price'] = $min_price_product[0][0]['Price'];
							}
						else
							{
								$min_price_product[0][0]['Price'] ="";
							}
					}
							if(isset($min_price_product[0][0]['Price']) and ($min_price_product[0][0]['Price']))
								{
									$master_row = $this->MasterProduct->find('all', 
									array('conditions'=>'MasterProduct.price="'.$min_price_product[0][0]['Price'].'" and product_id="'.$product_id.'"', 
										  'order'=>'MasterProduct.created Desc', 'limit'=>'1'));
									if(isset($master_row[0]) and ($master_row[0]))
										{
											return $master_row[0]['MasterProduct']; 	
										}
								}
								else
								{
									return false;
								}
				}
			else
				{
					return false;
				}
		}
		
		
	function __get_product_seller_price($product_id="", $seller_id = "")
	{
			$master_row = $this->MasterProduct->find('all', 
			array('conditions'=>'MasterProduct.seller_id ="'.$seller_id.'" and product_id="'.$product_id.'"', 
				  ));
			if(isset($master_row[0]) and ($master_row[0]))
				{
					return $master_row[0]['MasterProduct']; 	
				}
	}
	
	function __new_price_offer_list($product_id)
	{
			$master_row = $this->MasterProduct->find('all', 
			array('conditions'=>'MasterProduct.product_id="'.$product_id.'" and MasterProduct.conditions="1"', 
				  'order'=>'MasterProduct.created Desc'));
				  if(isset($master_row) and ($master_row))
					  {
						  $x=0;
						  foreach($master_row as $master)
						  {
							$seller = $this->Seller->findById($master['MasterProduct']['seller_id']);
							$master_row[$x]['MasterProduct']['Seller'] = $seller['Seller'];  
							$x++;
						  }
					  }
			return $master_row;

	}
	
	function __used_price_offer_list($product_id)
		{
			$master_row = $this->MasterProduct->find('all', 
			array('conditions'=>'MasterProduct.product_id="'.$product_id.'" and 
			                    (MasterProduct.conditions="3" or MasterProduct.conditions="4" or MasterProduct.conditions="5")', 
				                'order'=>'MasterProduct.created Desc'));
			  if(isset($master_row) and ($master_row))
				  {
					  $x=0;
					  foreach($master_row as $master)
					  {
						$seller = $this->Seller->findById($master['MasterProduct']['seller_id']);
						$master_row[$x]['MasterProduct']['Seller'] = $seller['Seller'];  
						$x++;
					  }
				  }
			return $master_row;
		}
	
	function __Collectible_price_offer_list($product_id)
		{
			$master_row = $this->MasterProduct->find('all', 
			array('conditions'=>'MasterProduct.product_id="'.$product_id.'" and 
			                    (MasterProduct.conditions="6" or MasterProduct.conditions="7" or MasterProduct.conditions="8" 
								 or MasterProduct.conditions="9")', 
				                'order'=>'MasterProduct.created Desc'));
			  if(isset($master_row) and ($master_row))
				  {
					  $x=0;
					  foreach($master_row as $master)
					  {
						$seller = $this->Seller->findById($master['MasterProduct']['seller_id']);
						$master_row[$x]['MasterProduct']['Seller'] = $seller['Seller'];  
						$x++;
					  }
				  }
			return $master_row;
		}

	function __Refurbished_price_offer_list($product_id)
		{
			$master_row = $this->MasterProduct->find('all', 
			array('conditions'=>'MasterProduct.product_id="'.$product_id.'" and 
			                    (MasterProduct.conditions="2")', 
				                'order'=>'MasterProduct.created Desc'));
			  if(isset($master_row) and ($master_row))
				  {
					  $x=0;
					  foreach($master_row as $master)
					  {
						$seller = $this->Seller->findById($master['MasterProduct']['seller_id']);
						$master_row[$x]['MasterProduct']['Seller'] = $seller['Seller'];  
						$x++;
					  }
				  }
								//pr($master_row);
								//exit;
			return $master_row;
		}
	
	function _product_condition_price_min($product_id="", $condition="")
		{
			if($condition=="Used")
				{
					$condition_id = "conditions = '3' or conditions = '4' or conditions = '5'";
				}
			else if($condition=="new")
				{
					$condition_id = "conditions = '1'";	
				}
			else if($condition=="Refurbished")
				{
					$condition_id = "conditions = '2'";	
				}
			else if($condition=="Collectible")
				{
					$condition_id = "conditions = '6' or conditions = '7' or conditions = '8'  or conditions = '9'";
				}
			//echo "Select min(price) as Price from master_products where product_id=".$product_id." and (".$condition_id.") ";
			$min_price_product = $this->MasterProduct->query("Select min(price) as Price from master_products where product_id=".$product_id." and (".$condition_id.") ");
			return $min_price_product;
		}
		
		
	function _product_condition_price_max($product_id="", $condition="")
		{
			$min_price_product = $this->MasterProduct->query("Select max(price) as Price from master_products where product_id=".$product_id." and conditions = ".$condition." ");
			return $min_price_product;
		}
		
	function _get_seller_id($user_id)
		{
			$seller_id = $this->Seller->findByUserId($user_id, array('fields'=>'Seller.id'));
			return $seller_id['Seller']['id'];
		}
		
		
	function _get_user_image($pic_url="")
	{
		if(isset($pic_url) and $pic_url)
			{
				$picurl = $pic_url;
				$d_width = 300;
				$d_height = 300;
				
			}
			else
			{
				$website_image_url = Configure::read('Website.image_url');
				$picurl = $website_image_url.'img/default_per.png';
				$d_width = 218;
				$d_height = 218;

			}
		$user_id = uniqid();	
		$time = rand().time();	
		  if(!@imagecreatefromjpeg($picurl))
			  {    
				if(!@imagecreatefromgif($picurl))
					{
					  if(!@imagecreatefrompng($picurl))
					  {
						if(!@imagecreatefromwbmp($picurl))
						{
						  $invalid="yes";
						  $picerror="yes";
						}
						else
						{
						  $src = imagecreatefromwbmp($picurl);
						  $extension = "bmp";
						  $invalid="no"; 
						}
					  }
					  else
					  {
						$src = imagecreatefrompng($picurl);
						$extension = "png"; 
						$invalid="no";     
					  }
					}
					else
					{
					  $src = imagecreatefromgif($picurl);
					  $extension = "gif";  
					  $invalid="no";    
					}
				 }
			  else
				  {
					$src = imagecreatefromjpeg($picurl);
					$extension = "jpg";  
					 $invalid="no";   
				  }
					  if($invalid!="yes")
							  {
								list($width,$height)=getimagesize($picurl);
								$newwidth=$d_width;
								$newheight=($height/$width)*$d_height;
								$tmp=imagecreatetruecolor($newwidth,$newheight);
								imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
								
								$folder_url = WWW_ROOT.'img/User/';
										if(!is_dir($folder_url)) {
												mkdir($folder_url);
											}
								$filePath = $folder_url.$user_id.'_'.$time.'.'.$extension ;
								imagejpeg($tmp,$filePath,100);
								imagedestroy($src);
								imagedestroy($tmp);

						  if(!@imagecreatefromjpeg($picurl))
								  {
									if(!@imagecreatefromgif($picurl))
									{
									  if(!@imagecreatefrompng($picurl))
									  {
										if(!@imagecreatefromwbmp($picurl))
										{
										  $invalid="yes";
										  $picerror="yes";
										}else{
										  $src = imagecreatefromwbmp($picurl);
										  $extension = "bmp";
										}
									  }
									  else
									  {
										$src = imagecreatefrompng($picurl);
										$extension = "png";     
									  }
									}else{
									  $src = imagecreatefromgif($picurl);
									  $extension = "gif";     
									}
								  }else{
							$src = imagecreatefromjpeg($picurl);
							$extension = "jpg";     
						  }
																					  
								$newwidth=$d_width;
								$newheight=($height/$width)*$d_height;
								$tmp=imagecreatetruecolor($newwidth,$newheight);
								imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
								$folder_url = WWW_ROOT.'img/User/';
										if(!is_dir($folder_url)) {
												mkdir($folder_url);
											}
								$filePath = $folder_url.$user_id.'_'.$time.'.'.$extension ;
								imagejpeg($tmp,$filePath,100);
								imagedestroy($src);
								imagedestroy($tmp);
								$filename = $user_id.'_'.$time.'.'.$extension ;
								$picture = $filename;
								return $picture;
						  }
	}
	function load_menu($menu_id)
		{
			$menu_details = $this->__get_menu($menu_id);
			return $menu_details;
		}

	
	function _menu_details($menu_id)
		{
			 $menu_details=$this->Menu->findById($menu_id);
			 return $menu_details;
		}
	function __users_list_all()
		{
			$users_list=$this->User->find('all');
			return $users_list; 
		}
	function __pages_list()
		{
			$pages_list=$this->Page->find('all');
			return $pages_list; 
		}
		
	function __menu_list()
		{
			$menu_list=$this->Menu->find('all');
			return $menu_list; 
		}
		
	/* Mostly Used _get functions*/
	function _get_parent_categories()
	{
		$categories = $this->Category->find('all',array('conditions'=>'Category.pid=0 and Category.status=1', 'fields'=>'Category.id, Category.slug, Category.name'));
		return $categories;
	}
	function _sub_catecategories($category_id, $limit="")
	{
		$Sub_categories = $this->Category->find('all',
								array('conditions'=>'Category.pid="'.$category_id.'" and Category.status=1', 
										'fields'=>'Category.*', 
										'limit'=>$limit));;
		return $Sub_categories;
	}
	
	function _get_subcatecategories($category_id, $limit="")
	{
		$Sub_categories = $this->Category->find('all',
								array('conditions'=>'Category.pid="'.$category_id.'" and Category.status=1', 
										'fields'=>'Category.*', 
										'limit'=>$limit));;
		return $Sub_categories;
	}
	function _get_categories()
		{
				$categories = $this->Category->find('all',
				array('conditions'=>'Category.status=1', 
				'fields'=>'Category.*', 
				));
				return $categories;
		}

	function _menu_name($menu_id) {
		$menu_name=$this->Menu->findById($menu_id);
		return $menu_name['Menu']['menu_title'];
	}

	function _parent_item_name($parent_id) {
		$menu_name=$this->MenuItem->findById($parent_id);
		return $menu_name['MenuItem']['item_title'];
	}

	function __get_slug_to__id($slug, $model){
		$id = $this->$model->findBySlug($slug);
		return $id[$model]['id'];
	}
	function __get_details($id,$model){
		$details=$this->$model->findById($id);
		return $details;
	}
	function __get_detils($id,$model){
		$details=$this->$model->findById($id);
		return $details;
	}
	function __getUserDetails($user_id)
		{
			$UserDetails = $this->User->findById($user_id);
			return $UserDetails;
		}
	function __get_slug_from_id($id, $model){
		$slug=$this->$model->findById($id);
		return $slug[$model]['slug'];
	}
	
	function __slug_to_user_id($slug)
		{
		  $user_id=$this->User->findBySlug($slug);
		  return $user_id['User']['id'];
		}
		
	function _list_departments($limit = "")
		{
			$subdivisions = $this->Department->find("all",
														array(
															   'conditions' => '',
															   'fields' => array('Department.id','Department.name',
															  ), 'limit'=>$limit));
			$result = Set::combine($subdivisions, '{n}.Department.id','{n}.Department.name');		
			return $result;
		}
	function __list_message_subjects($limit = "")
		{
				$subdivisions = $this->MessageSubject->find("all",
															array(
																   'conditions' => '',
																   'fields' => array('MessageSubject.id','MessageSubject.name',
																  ), 'limit'=>$limit));
				$result = Set::combine($subdivisions, '{n}.MessageSubject.id','{n}.MessageSubject.name');		
				return $result;

		}
	
	function _list_categories($limit = "")
		{
			$subdivisions = $this->Category->find("all",
														array(
															   'conditions' => '',
			 												   'fields' => array('Category.id','Category.name',
															  ), 'limit'=>$limit));
			$result = Set::combine($subdivisions, '{n}.Category.id','{n}.Category.name');		
			return $result;
		}
		
	function _list_parent_categories($limit = "")
		{
			$subdivisions = $this->Category->find("all",
														array(
															   'conditions' => 'Category.pid=0',
			 												   'fields' => array('Category.id','Category.name',
															  ), 'limit'=>$limit));
			$result = Set::combine($subdivisions, '{n}.Category.id','{n}.Category.name');		
			return $result;
		}
		
		
		
	function __get_user_id($hash)
	{
		 $user_id =  $this->User->findByHash($hash, array('fields'=>'User.id'));
		 return  $user_id['User']['id']; 
	}
		
	function _list_brands($limit = "", $cat_id="")
		{
			if(isset($cat_id) and ($cat_id))
				{
					$conditions = 'Brand.cat_id = "'.$cat_id.'"';
				}
				else
				{
					$conditions = '';
				}
			$subdivisions = $this->Brand->find("all",
														array(
															   'conditions' => ''.$conditions.'',
			 												   'fields' => array('Brand.id','Brand.name',
															  ), 'limit'=>$limit));
															 // pr(	$subdivisions);
															  //exit;
			$result = Set::combine($subdivisions, '{n}.Brand.id','{n}.Brand.name');		
			return $result;
		}
		
	function _list_products($limit = "")
		{
			$subdivisions = $this->Product->find("all",
														array(
															   'conditions' => '',
			 												   'fields' => array('Product.id','Product.name',
															  ), 'limit'=>$limit));
			$result = Set::combine($subdivisions, '{n}.Product.id','{n}.Product.name');		
			return $result;
		}

	function _list_stock_status($limit = "")
		{
			$subdivisions = $this->StockStatus->find("all",
														array(
															   'conditions' => '',
			 												   'fields' => array('StockStatus.id','StockStatus.name',
															  ), 'limit'=>""));
			$result = Set::combine($subdivisions, '{n}.StockStatus.id','{n}.StockStatus.name');		
			return $result;
		}
	
	function _list_attributes($limit = "", $gp_id="")
		{
			if(isset($gp_id) and ($gp_id))
				{
					$conditiion = 'Attribute.attr_gp_id="'.$gp_id.'"';
				}
			else{
				$conditiion = '';
			}
			$subdivisions = $this->Attribute->find("all",
														array(
															   'conditions' => ''.$conditiion.'',
			 												   'fields' => array('Attribute.id','Attribute.name',
															  ), 'limit'=>""));
			$result = Set::combine($subdivisions, '{n}.Attribute.id','{n}.Attribute.name');		
			return $result;
		}
	
	
	
		
	function _list_cities($limit = "")
		{
			$subdivisions = $this->City->find("all",
														array(
			 												   'fields' => array('City.id','City.name',
															  ), 'limit'=>$limit));
			$result = Set::combine($subdivisions, '{n}.City.id','{n}.City.name');		
			return $result;
		}
	function _list_shipping_service_providers($limit = "")
		{
			$subdivisions = $this->ShippingSp->find("all",
														array( 'conditions' => 'ShippingSp.status="1"',
			 												   'fields' => array('ShippingSp.id','ShippingSp.name',
															  ), 'limit'=>$limit));
			$result = Set::combine($subdivisions, '{n}.ShippingSp.id','{n}.ShippingSp.name');		
			return $result;
		}
	
		
	function _list_pages()
		{
			$subdivisions = $this->Page->find("all",array('Page' => '', 'fields' => array('Page.id','Page.page_title')));
			$result = Set::combine($subdivisions, '{n}.Page.id','{n}.Page.page_title');		
			return $result;
		}
	
	function _details_menu_item($id) {
			$menu_item=$this->MenuItem->findById($id);
			return $menu_item;
		}

	function __product_price_list($product_id="")
		{
			$product_details['Product']['id'] = $product_id;
			$new_MasterProduct = $this->_product_condition_price_min($product_details['Product']['id'], 'new');
			//pr($new_MasterProduct);
			//exit;
			$new_price_list = $this->__new_price_offer_list($product_id);	
			if(isset($new_MasterProduct[0][0]['Price']) and ($new_MasterProduct[0][0]['Price']))
				{
					$price_list[1]['name'] = "new";
					$price_list[1]['count'] = count($new_price_list)." New";
					$price_list[1]['new'] = $new_MasterProduct[0][0]['Price'];
				}
			$Used_MasterProduct = $this->_product_condition_price_min($product_details['Product']['id'], 'Used');
			$used_price_list = $this->__used_price_offer_list($product_id);
			if(isset($Used_MasterProduct[0][0]['Price']) and ($Used_MasterProduct[0][0]['Price']))
				{
					$price_list[2]['count'] = count($used_price_list)." Used";
					$price_list[2]['name'] = "Used";
					$price_list[2]['Used'] = $Used_MasterProduct[0][0]['Price'];
				}
			$Refurbished_MasterProduct = $this->_product_condition_price_min($product_details['Product']['id'], 'Refurbished');
			$Refurbished_price_list = $this->__Refurbished_price_offer_list($product_id);
			if(isset($Refurbished_MasterProduct[0][0]['Price']) and ($Refurbished_MasterProduct[0][0]['Price']))
				{
					$price_list[3]['name'] = "Refurbished";
					$price_list[3]['count'] = count($Refurbished_price_list)." Refurbished";
					$price_list[3]['Refurbished'] = $Refurbished_MasterProduct[0][0]['Price'];
				}
				
			$Collectible_MasterProduct = $this->_product_condition_price_min($product_details['Product']['id'], 'Collectible');
			$Collectible_price_list = $this->__Collectible_price_offer_list($product_id);	
			if(isset($Collectible_MasterProduct[0][0]['Price']) and ($Collectible_MasterProduct[0][0]['Price']))
				{
					$price_list[5]['count'] = count($Collectible_price_list)." Collectible";
					$price_list[5]['name'] = "Collectible";
					$price_list[5]['Collectible'] = $Collectible_MasterProduct[0][0]['Price'];
					
				}
			return $price_list;
		}
	
	
	function __list_countries($limit="")
	{
			$subdivisions = $this->Country->find("all",
														array(
			 												   'fields' => array('Country.id','Country.country_name',
															  ), 'limit'=>$limit));
			$result = Set::combine($subdivisions, '{n}.Country.id','{n}.Country.country_name');		
			return $result;
	}
	
	function __List_code_countries($limit="")
		{
			$subdivisions = $this->Country->find("all",
														array(
			 												   'fields' => array('Country.country_code','Country.country_name',
															  ), 'limit'=>$limit, 'order'=>'Country.country_name ASC'));
			$result = Set::combine($subdivisions, '{n}.Country.country_code','{n}.Country.country_name');		
			return $result;
		}
		
	function __List_code_states($limit="")
		{
			$subdivisions = $this->State->find("all",
														array(
			 												   'fields' => array('State.code','State.state',
															  ), 'limit'=>$limit,'order'=>'State.state ASC'));
			$result = Set::combine($subdivisions, '{n}.State.code','{n}.State.state');		
			return $result;
		}
		
	function __List_Group_attributes($limit="")
		{
			$subdivisions = $this->AttrGroup->find("all",
														array(
			 												   'fields' => array('AttrGroup.id','AttrGroup.name',
															  ), 'limit'=>$limit,'order'=>'AttrGroup.id ASC'));
			$result = Set::combine($subdivisions, '{n}.AttrGroup.id','{n}.AttrGroup.name');		
			return $result;
		}
		
	function __list_pr_conditions($limit="")
		{
				$subdivisions = $this->ProductCondition->find("all",
															array(
																		'conditions'=>'ProductCondition.status=1',
																		'fields' => array('ProductCondition.id','ProductCondition.name',
																		), 'limit'=>$limit));
				$result = Set::combine($subdivisions, '{n}.ProductCondition.id','{n}.ProductCondition.name');		
				return $result;
		}

	
	
	function __list_shipping_sps($limit="")
	{
			$subdivisions = $this->ShippingSp->find("all",
														array(
			 												   'fields' => array('ShippingSp.id','ShippingSp.name',
															  ), 'limit'=>$limit));
			$result = Set::combine($subdivisions, '{n}.ShippingSp.id','{n}.ShippingSp.name');		
			return $result;
	}
	
	function _get_stock_position($stock_id)
	{
		$stock = $this->StockStatus->findById($stock_id);
		return $stock['StockStatus']['name'];
	}
	
	function _get_brand_name($brand_id)
	{
		//brand_id
		$brand_name = $this->Brand->findById($brand_id); 
		return $brand_name['Brand']; 
	}
	
	function _brand_product($brand_slug)
		{
			$brand_id = $this->__get_slug_to__id($brand_slug, "Brand"); 
			$this->paginate['Product'] =array('conditions' => 'Product.brand_id="'.$brand_id.'"',
				'limit' => 24,
				'fields' => array('Product.*') ,
				'order' => 'Product.created Desc'
			  );
			return $Product_list = $this->paginate('Product');
	
		}
	
	function _get_products($cat_id,$limit="")
		{
			if(isset($cat_id) and sizeof($cat_id) and $cat_id)
				{
					$this->paginate['Product'] =array('conditions' => 'Product.cat_id='.$cat_id.'',
													'limit' => $limit,
													'fields' => array('Product.*') ,
													'order' => 'Product.created Desc'
												  );
			  $Product_list = $this->paginate('Product');
			  return $Product_list = $this->paginate('Product');
				}
			else
				{
					$this->paginate['Product'] =array('conditions' => '',
													'limit' => $limit,
													'fields' => array('Product.*') ,
													'order' => 'Product.created Desc'
												  );
					$Product_list = $this->paginate('Product');
					return $Product_list = $this->paginate('Product');
				}
		}
		
		function __get_product_rating($product_wisn="")
			{
				$product_id = $this->__get_product_id_from_wisn($product_wisn);
				
				$product_ratings = $this->ProductReview->find('all', array('conditions'=>'ProductReview.product_id='.$product_id.' 
																							and ProductReview.status = "1"',
																		   'fields'=>'ProductReview.rating'));
				if(isset($product_ratings) and ($product_ratings))
					{														
						$total_rate = 0;
						$x=0;
						foreach($product_ratings as $product_ratin)
							{
								$total_rate = ($total_rate+$product_ratin['ProductReview']['rating']);
								$x++;
							}
						(int)$total_rate;
						$avg_rating = 	($total_rate/$x);
						if(isset($avg_rating) and ($avg_rating))
							{
								$round_avg_rating = round($avg_rating,1);
								$round_avg_rating ;
								$exp_round_avg_rating = explode('.',$round_avg_rating);
								if(isset($exp_round_avg_rating[1]) and ($exp_round_avg_rating[1]))
									{
											$last_decimal = $exp_round_avg_rating[1];
											if($last_decimal>5)
												{
													$round_avg_rating = round($avg_rating);
												}
											else if($last_decimal<5)
												{
													$round_avg_rating = floor($avg_rating);
												}
											else
												{
													$round_avg_rating =  str_replace('.','_',$round_avg_rating);
												}
									}
								else
									{
										$round_avg_rating = $exp_round_avg_rating[0];
									}
							}
						else
							{
								$round_avg_rating = 0;
							}
					}
				else
					{
						$round_avg_rating = 0;
					}
				//echo $round_avg_rating;
				return $round_avg_rating;
			}
		
		function _get_top_5_sellers()
			{
				$sellers_ids = $this->SellerFeedback->query('SELECT seller_id FROM seller_feedbacks GROUP BY seller_id
															HAVING (
															avg( rating ) > 4.75
															)
															ORDER BY avg( rating ) DESC
															LIMIT 0 , 4 '
															);
			return $sellers_ids; 										
			}
		
		function _list_states($limit = "")
		{
			$subdivisions = $this->State->find("all",
														array(
															   'conditions' => '',
			 												   'fields' => array('State.id','State.state',
															  ), 'limit'=>$limit));
			$result = Set::combine($subdivisions, '{n}.State.id','{n}.State.state');		
			return $result;
		}
		
		function __list_options($limit="")
		{
			$subdivisions = $this->Option->find("all",
														array(
															   'conditions' => '',
			 												   'fields' => array('Option.slug','Option.name',
															  ), 'limit'=>$limit));
															  
															 //pr($subdivisions);
															 // exit;
			$result = Set::combine($subdivisions, '{n}.Option.slug','{n}.Option.name');		
			return $result;
		}
	
	function _get_catpercentage($cat_id="")
		{
			$price_percentage = $this->Category->findById($cat_id, array('fields'=>'Category.price_percentage')); 
			return $price_percentage['Category']['price_percentage']; 
		}
	
	
	function _get_seller_user_id($seller_id)
		{
			$seller = $this->Seller->findById($seller_id);
			return $seller['Seller']['user_id'];
		}
		
	function _primary_cal_price($percentage="", $product_price="")
		{
			$primary_cal_price = (($percentage*$product_price)/100);
			return $primary_cal_price; 
		}
	function _merchant_cal_price($percentage="",$product_price="" )
		{
			$primary_cal_price = (($percentage*$product_price)/100);
			$merchant_call_price = ($product_price-$primary_cal_price);
			return $merchant_call_price; 
		}
	
	function _getPayPalEmail($user_id)
		{
			$PayPal_Email = $this->Paypal->findByUserId($user_id);
			return $PayPal_Email['Paypal']['paypal_email'];
		}
	
	function _get_parent_detail($pid, $model)
		{
			$array = $this->$model->findById($pid);
			return $array;
		}
	function _get_product_condition($condition_id)
		{
			$array = $this->ProductCondition->findById($condition_id);
			return $array['ProductCondition'];
		}
	function __get_parent_id($cat_id, $model)
		{
			$cat = $this->$model->findById($cat_id);
			return $cat[$model]['pid']; 
		}
	function _get_sublings($pid, $model)
		{
			if($pid)
			{
				$pid = $pid; 
			}
			else
			{
				$pid = 0;
			}
			$array = $this->$model->find('all', array('conditions'=>$model.'.pid='.$pid));
			if(isset($array) and sizeof($array))
			{
				$array = $array; 
			}
			else
			{
				$array = "";
			}
			return $array;
		}
	function _get_childrens($id, $model)
		{
			if($id)
			{
				$id = $id; 
			}
			else
			{
				$id = 0;
			}
			$array = $this->$model->find('all', array('conditions'=>$model.'.pid='.$id));
			if(isset($array) and sizeof($array))
			{
				$array = $array; 
			}
			else
			{
				$array = "";
			}
	
		}
		
	function __list_attr_groups($limit="")
		{
			$subdivisions = $this->AttrGroup->find("all",array('conditions' => '',
			'fields' => array('AttrGroup.id','AttrGroup.name'),
			'limit'=>$limit));
			$result = Set::combine($subdivisions, '{n}.AttrGroup.id','{n}.AttrGroup.name');		
			return $result;
		}
	function __get_attr_name($attr_id="")
		{
			$attr = $this->Attribute->findById($attr_id);
			return $attr;
		}
	function _get_group_attr($AttrGroup_id="")
		{
			$AttrGroup = $this->AttrGroup->findById($AttrGroup_id);
			return $AttrGroup;
		}
	
	function _list_users($limit="")
		{
				$subdivisions = $this->User->find("all",array('conditions' => '',
				'fields' => array('User.id','User.name'),
				'limit'=>$limit));
				$result = Set::combine($subdivisions, '{n}.User.id','{n}.User.name');		
				return $result;
		}
		
		
	function upload_img($insert_id="", $file, $folder_name)
		{
			if(isset($insert_id) and ($insert_id))
				{
					 $folder = $insert_id;
				}
			else
				{
					$folder = "";	
				}
		 
		  $current_dir = getcwd();
		  $projects_dir = WWW_ROOT.'img/'.$folder_name.'/';
		  
			if(!is_dir($projects_dir)) {
				mkdir($projects_dir);
			}
			if(isset($folder) and ($folder))
				{
				   $folder_url = $projects_dir.$folder;
				}
			else
				{
					$folder_url = $projects_dir;
				}
			if(!is_dir($folder_url)) {
				mkdir($folder_url);
			}
		//foreach($formdata as $file) {
			// replace spaces with underscores
			if(isset($file['name']) and $file['name'])
				{
					$filename = str_replace(' ', '_', $file['name']);
				}
			// assume filetype is false
			$typeOK = true;
			// check filetype is ok
			// if file type ok upload the file
			if($typeOK) {
				// switch based on error code
				switch($file['error']) {
					case 0:
						// check filename already exists
						if(!file_exists($folder_url.'/'.$filename)) {
							// create full filename
							$full_url = $folder_url.'/'.$filename;
							$url = $folder.'/'.$filename;
							// upload the file
							$success = move_uploaded_file($file['tmp_name'], $full_url);
						} else {
							// create unique filename and upload file
							//ini_set('date.timezone', 'Europe/London');
							//$now = date('Y-m-d-His');
							$now = time();
							$now = $now."-";
							$full_url = $folder_url.'/'.$now.$filename;
							$url = $folder.'/'.$now.$filename;
							$success = move_uploaded_file($file['tmp_name'], $full_url);
						}
						// if upload was successful
						if($success) {
							// save the url of the file
							$result['urls'][] = $url;
						} else {
							$result['errors'][] = "Error uploaded ".$filename." Please try again.";
						}
						break;
					case 3:
						// an error occured
						$result['errors'][] = "Error uploading ".$filename." Please try again.";
						break;
					default:
						// an error occured
						$result['errors'][] = "System error uploading ".$filename." Contact webmaster.";
						break;
				}
			} elseif($file['error'] == 4) {
				// no file was selected for upload
				$result['nofiles'][] = "No file Selected";
			} else {
				// unacceptable file type
				$result['errors'][] = "$filename cannot be uploaded. Acceptable file types: gif, jpg, png.";
			}
		//}
		return $result;
	}
	
	function url_upload($folder_name, $url)
	{
		    $url = trim($url);
			if ($url) {
				$file = fopen($url, "rb");
				if ($file) {
					$directory  =  WWW_ROOT.'img/'.$folder_name.'/'; // Directory to upload files to.
					if(!is_dir($directory)) {
						mkdir($directory);
					}
					$valid_exts = array(
						"jpg",
						"jpeg",
						"gif",
						"png"
					); // default image only extensions
					$ext        = end(explode(".", strtolower(basename($url))));
					if (in_array($ext, $valid_exts)) {
						$rand     = rand(1000, 9999);
						$filename = $rand . date('ymd') . time() . basename($url);
						$filename = str_replace(',','_',$filename);
						$newfile  = fopen($directory . $filename, "wb"); 
						// creating new file on local server
						if ($newfile) {
							while (!feof($file)) {
								// Write the url file to the directory.
								fwrite($newfile, fread($file, 1024 * 8), 1024 * 8); 
								// write the file to the new directory at a rate of 8kb/sec. until we reach the end.
							}
							//echo 'File uploaded successfully! You can access the file here:' . "\n";
							//echo '' . $directory . $filename . '';
							return $filename; 
						} else {
							echo 'Could not establish new file (' . $directory . $filename . ') 
							on local server. Be sure to CHMOD your directory to 777.';
						}
					} else {
						echo 'Invalid file type. Please try another file.';
					}
				} else {
					echo 'Could not locate the file: ' . $url . '';
				}
			} else {
				echo 'Invalid URL entered. Please try again.';
			}

	}
	
	
	protected function format($data, $type = 'json') {
		switch ($type) {
			case 'php':
				$formated_data = serialize($data);
				break;
			default:
				$formated_data = json_encode($data);
		}
		
		return $formated_data;
	}
		
		 function _get_post_time($time_stamp)
		 {
			$row['TimeSpent'] = (time()-$time_stamp);
			$row['date_created'] = $time_stamp;

			$days = floor($row['TimeSpent'] / (60 * 60 * 24));
			$remainder = $row['TimeSpent'] % (60 * 60 * 24);
			$hours = floor($remainder / (60 * 60));
			$remainder = $remainder % (60 * 60);
			$minutes = floor($remainder / 60);
			$seconds = $remainder % 60;
			if($days > 0)
			return  date('F d Y', $row['date_created']);
			elseif($days == 0 && $hours == 0 && $minutes == 0)
			return "few seconds ago";		
			elseif($days == 0 && $hours == 0)
			return $minutes.' minutes ago';
			else
			return "few seconds ago";	
		 }
		 
	 function __IsAdminAuthorised() 
		 {
			 $admin = $this->Auth->User('is_admin');
			 if(isset($admin) and ($admin=='1'))
				 {
					 return true; 
				 }
				 else
				 {
						$this->redirect($this->Auth->logout());
				 }
		 }
		 
	function __IsSellerAuthorised()
		{
			// echo "ok";
			 $is_seller = $this->Auth->User('is_seller');
			 $user_id = $this->Auth->User('id');
			 if((isset($is_seller) and ($is_seller==1)))
				 {
					 //echo "ok";
					 
					 $seller_entry_exist = $this->Seller->find('first', array('conditions'=>'Seller.is_verified=1 and Seller.user_id = "'.$user_id.'"'));
					 if(isset($seller_entry_exist) and ($seller_entry_exist))
						{
							return true; 
						}
						else
						{
							$this->Session->setFlash('Your seller account is not yet approved by admin.');
							$this->redirect(array('controller'=>'users', 'action'=>'dashboard'));
						}
				 }
			 else
				 {
					$this->redirect($this->Auth->logout());
				 }
		}
	function _is_paypal_registred($user_id)
		{
			$paypal_user_exist = $this->Paypal->findByUserId($user_id);
			if(isset($paypal_user_exist) and ($paypal_user_exist))
				{
					return $paypal_user_exist;
				}
				else{
					return false;
				}
			
		}
		 
	function _get_user($slug)
		{
			$user = $this->User->findBySlug($slug);
			if(isset($user) and ($user))
				{
					$user = $user;
				}
			else
				{
					$user = $this->User->findById($slug);
				}
			
			if(isset($user['User']['password']) and ($user['User']['password']))
				{
					unset($user['User']['password']);
				}
			return $user;
	}
	

		
		function _get_parent_cat($cat_id)
			{
				$cat = $this->Category->findById($cat_id);
				
				if(isset($cat) and ($cat['Category']['pid']==0))
				{
					 $catParent['Category']['name'] = "Parent";
					  return  $catParent['Category']['name']; 
				}
				else
				{
					$catParent = $this->Category->findById($cat['Category']['pid']);
					return  $catParent['Category']['name'];
				}
			}
		function _get_parent($model = "", $limit="", $sort="")
			{
				$this->paginate[''.$model.''] = array(
														'conditions'=>''.$model.'.pid=0',
														'fields' => array(''.$model.'.*') ,
														'limit' => $limit,
														'order'=>$sort
													);
				$categories =  $this->paginate(''.$model.'') ;
				return $categories;	
			}
		
		/*
			* This function used in admin manage subcategories
		*/
		function _get_Sub($model ='', $slug="", $limit="")
			{
				$cat_id = $this->__get_slug_to__id($slug, ''.$model.'');

				$this->paginate[''.$model.''] = array(
													'conditions'=>''.$model.'.pid="'.$cat_id.'"',
													'limit' => $limit,
													'fields' => array(''.$model.'.*') ,
													'order'=>''.$model.'.id Asc'
													);
				$categories =  $this->paginate(''.$model.'') ;
				return $categories;	
			}
		/*
			* This function used in inbuit Sub categories front end 
		*/
		function _get_brands($limit="",$sort)
		{
				$this->paginate['Brand'] = array(
													'conditions'=>'',
													'limit' => $limit,
													'fields' => array('Brand.*') ,
													'order'=>$sort
													);
				$brands =  $this->paginate('Brand') ;
				$brands =  $this->paginate('Brand') ;
				return $brands;	
		}
		
	function _sub_menu_item($menuItem_id)
		{
			$_sub_menu_items = $this->MenuItem->find('all', array('conditions' => 'MenuItem.parent_id = '.$menuItem_id.' and published = 1'));
			return $_sub_menu_items;
		}	
		
	function __get_top_manu_items($menu_item__id)
		{
			$menu_items=$this->MenuItem->find('all', array('conditions' => 'MenuItem.id = '.$menu_item__id.' and published = 1'));
			$item_slug = $this->__get_page_slug($menu_items['0']['MenuItem']['page_id']);
			$menu_items['0']['MenuItem']['page_slug'] = $item_slug;
			$sub_menu_items = $this->_sub_menu_item($menu_items['0']['MenuItem']['id']);
			if(sizeof($sub_menu_items))
				{
					$i = 0;
					foreach($sub_menu_items as $sub_menu_item)
						{
							$item_slug = "";
							$item_page_id = $sub_menu_item['MenuItem']['page_id'];
							if($item_page_id > 0)
								{
									$item_slug = $this->__get_page_slug($item_page_id);
								}
							$sub_menu_item['MenuItem']['page_slug'] = $item_slug;
							$menu_items[0]['SubMenuItems'][$i] = $sub_menu_item;		
							$i++;
						}
							
				}			

			return $menu_items;
		}
		
		
	
	function __get_page_slug($page_id)
		{
			$page_slug = "";
			$page_details  =  $this->Page->findById($page_id, array('fields' => 'slug'));
			if(sizeof($page_details) and isset($page_details['Page']) and isset($page_details['Page']['slug']))
				$page_slug = $page_details['Page']['slug'];
				return $page_slug;
		}
	function __get_menu_items_front($menu_id)
		{
			$menu_items=$this->MenuItem->find('all', array('conditions' => 'MenuItem.menu_id = '.$menu_id.' and published = 1'));
			return $menu_items;
		}

	
		
	function __get_menu($menu_id)
		{
			$menu_details=$this->_menu_details($menu_id);
			$menu_title = $menu_details['Menu']['menu_title'];
			$menu_description = $menu_details['Menu']['menu_description'];
			
			$menu_items = $this->__get_menu_items_front($menu_id);
			//pr($menu_items);
			if(sizeof($menu_items))
				{
					$i = 0;
					foreach($menu_items as $menu_item)
						{
							$item_slug = "";
							$item_page_id = $menu_item['MenuItem']['page_id'];
							if($item_page_id > 0)
								{
									$item_slug = $this->__get_page_slug($item_page_id);
								}
							$menu_items[$i]['MenuItem']['page_slug'] = $item_slug;
							$i++;
						}
					$menu_details['MenuItemsList'] = $menu_items;
				}
			return $menu_details;
		}

		
		
		function __get_product_id_from_wisn($product_wisn)
			{
				
				$product_id = $this->Product->findByWisn($product_wisn, array('fields'=>'Product.id'));
				return $product_id['Product']['id'];
			}
		
		function _exiting_seller_offer($selller_id, $product_id)
			{
				$exist = $this->MasterProduct->find('first',
				 array('conditions'=>'MasterProduct.seller_id='.$selller_id.' and MasterProduct.product_id='.$product_id.'',
				 'fields'=>'MasterProduct.id'))  ;
				 return $exist;
			}
		
		
		function _get_seller($seller_id)
			{
				$seller = $this->Seller->findById($seller_id);	
				return $seller;
			}
			
			
		function wisn_product($product_id="")
			{
				$product_details = $this->Product->findById($product_id);
				if(isset($product_details) and ($product_details))
					{
						$category = $this->Category->findById($product_details['Product']['cat_id']);
						$product_details['Product']['category']= $category['Category']; 
						$stock_detail = $this->_get_stock_position($product_details['Product']['stock']);
						$product_details['Product']['stock_detail']= $stock_detail; 
						$MasterProduct = $this->__get_product_min_price($product_details['Product']['id']);
						$seller = $this->_get_seller($MasterProduct['seller_id']); 
						$MasterProduct['Seller'] = $seller['Seller']; 
						$product_details['Product']['MasterProduct']= $MasterProduct;
						$brand_name = $this->_get_brand_name($product_details['Product']['brand_id']);
						$product_details['Product']['Brand'] = $brand_name; 
						$ratings = $this->__get_product_rating($product_details['Product']['wisn']);
						$product_details['Product']['rating'] = $ratings;
						$product_price_offers = $this->__product_price_list($product_details['Product']['id']);
						$product_details['Product']['offers'] = $product_price_offers;
						return $product_details;
					}
	
			}
		
		
		function _get_ups_service_name($service_code)
			{
				$ups_settings = $this->UpsShipping->findByName('UPS');
				$ups_settings_services = $ups_settings['UpsShipping']['services'];
				$ups_settings_services_exp = explode(',',$ups_settings_services);
				if($ups_settings_services_exp):
					foreach($ups_settings_services_exp as $ups_service)
						{
							$Key_Value_array = explode('-',$ups_service);
							if($Key_Value_array[0]==$service_code)
								{
									$serv_name[] = str_replace('_',' ',$Key_Value_array[1]);
								}
						}
					if(isset($serv_name[0]) and ($serv_name[0]))
						{
							return $serv_name[0];
						}
				endif;	
			}
			
		function _get_fedex_service_name($service_code)
			{
				$ups_settings = $this->FedexShipping->findByName('FEDEX');
				$ups_settings_services = $ups_settings['FedexShipping']['services'];
				$ups_settings_services_exp = explode(',',$ups_settings_services);
				if($ups_settings_services_exp):
					foreach($ups_settings_services_exp as $ups_service)
						{
							$Key_Value_array = explode('-',$ups_service);
							if($Key_Value_array[0]==$service_code)
								{
									$serv_name[] = str_replace('_',' ',$Key_Value_array[1]);
								}
						}
					if(isset($serv_name[0]) and ($serv_name[0]))
						{
							return $serv_name[0];
						}
				endif;	
			}
			
		function __Seller_Sentmail($user_id, $start_date = "", $end_date = "")
		{
				if((isset($start_date) and ($start_date)) and (isset($end_date) and ($end_date))){
					$condition = 'and created >= "'.$start_date.'" and created <= "'.$end_date.'"'; 
				}
				else
				{
					$condition ='';
				}
			
			
			 $this->paginate['Message'] =  array('conditions' => 'Message.from_user_id = "'.$user_id.'" '.$condition.'',
				'limit' => 24,
				'fields' => array('Message.*') ,
				'order' => 'Message.created Desc'
				);
				
				$messages = $this->paginate('Message');
				$x =0;
				foreach($messages as $message)
					{
						$user = $this->User->findById($message['Message']['to_user_id']);
						$messages[$x]['Message']['User'] = $user['User']; 
						$userfrom_user_id = $this->User->findById($message['Message']['from_user_id']);
						$messages[$x]['Message']['FromUser'] = $userfrom_user_id['User']; 
						$get_subject = $this->MessageSubject->findById($message['Message']['subject_id']);
						$messages[$x]['Message']['Subject'] =$get_subject['MessageSubject']['name']; 

						$x++;
					}
					return $messages;
		}
		
		function __Seller_Recievedmail($user_id, $start_date = "", $end_date = "")
			{
				
				if((isset($start_date) and ($start_date)) and (isset($end_date) and ($end_date))){
					$condition = 'and created >= "'.$start_date.'" and created <= "'.$end_date.'"'; 
				}
				else
				{
					$condition ='';
				}
			 $this->paginate['Message'] =  array('conditions' => 'Message.to_user_id = "'.$user_id.'" '.$condition.'',
				'limit' => 24,
				'fields' => array('Message.*') ,
				'order' => 'Message.created Desc'
				);
				
				$messages = $this->paginate('Message');
				$x =0;
				foreach($messages as $message)
					{
						$user = $this->User->findById($message['Message']['from_user_id']);
						$messages[$x]['Message']['ToUser'] = $user['User']; 
						$get_subject = $this->MessageSubject->findById($message['Message']['subject_id']);
						$messages[$x]['Message']['Subject'] =$get_subject['MessageSubject']['name']; 
						$x++;
					}
					return $messages;
			}
		function _last_dates($count="", $type=""){
			
				$format = 'Y-m-d';
				$date = date ( $format );
				if(isset($type) and ($type=='d'))
					{
						// - 7 days from today
						$final_return_date =  date ( $format, strtotime ( '-'.$count.' day' . $date ) );
					}
				elseif(isset($type) and ($type=='Y'))
					{	
					// - 1 month from today
					
						$final_return_date = date ( $format, strtotime ( '-'.$count.' year' . $date ) );
					}
					return $final_return_date;
		}
		
		function _get_seller_orders($conditions="")
			{
				
				$this->paginate['OrderItem'] =array('conditions' => $conditions,
													'limit' => 10,
													'order'=>"OrderItem.id Desc",
												  );
					$Order_list = $this->paginate('OrderItem');
					$x=0;
					foreach($Order_list as $list)
						{
							$order = $this->Order->findById($list['OrderItem']['order_id']);
							$address = $this->Address->findBYId($order['Order']['shipping_address_id']);
							$order['Address'] = $address['Address']; 
							$country = $this->Country->findById($order['Address']['country']);
							$order['Address']['CountryName'] = $country['Country']['country_name'];
							$Order_list[$x]['Order'] = $order;
							$product = $this->Product->findById($list['OrderItem']['product_id']);
							$ratings = $this->__get_product_rating($product['Product']['wisn']);
							$product['Product']['rating'] = $ratings;
							$stock_detail = $this->_get_stock_position($product['Product']['stock']);
							$product['Product']['stock_detail']= $stock_detail; 
							$MasterProduct = $this->__getPaid_product_min_price($product['Product']['id'], $list['OrderItem']['seller_id']);
							if(isset($MasterProduct) and ($MasterProduct))
								{
									$product_condition  = $this->_get_product_condition($MasterProduct['conditions']);
									$product['Product']['condition'] = $product_condition;
									$product['Product']['MasterProduct'] = $MasterProduct;
								}
							
							$Order_list[$x]['Product'] = $product['Product'];
							
							$x++;
						}
						return $Order_list;
			
			}
			
		function _unshipped_seller_orders($seller_id)
			{
				$orders = $this->OrderItem->find('all',
				array('conditions'=>'OrderItem.seller_id ="'.$seller_id.'" and OrderItem.shipped = "0" and OrderItem.payment_status = "1"'));
				return $orders;
			}
			
		function _getAttributes($table) {
			$sql = "SHOW FIELDS FROM `" . strtolower($table) . "`";
			$ts = mysql_query($sql);
			$cts = mysql_num_rows($ts);
			while ($ats = mysql_fetch_array($ts)) {
			$attr_array[] = $ats['Field'];
			}
			if (isset($attr_array) and ($attr_array)) {
			return $attr_array;
			} else {
			return false;
			}
		}
	
		function _get_seller_shipping_rate($weight, $seller_id)
			{
				$ship_price_w_lb = $this->Seller->findById($seller_id,
									array('fields'=>'Seller.ship_price_w_lb'));
									//pr($ship_price_w_lb);
									//exit;
					  $exp_1 =  explode(', ',$ship_price_w_lb['Seller']['ship_price_w_lb']);
					 // pr(  $exp_1);
					  if(isset( $exp_1) and ( $exp_1))
						  {
								  $i=0;
								  foreach( $exp_1 as  $exp_2)
									  {
										$exp_1_from_nm = explode('-',$exp_2);
										//pr($exp_1_from_nm);
										
										
										$exp_1_from =  $exp_1_from_nm[0];
										//pr($exp_1_from);
										
										$exp_1_from_1 = explode('_',$exp_1_from_nm[1]);
										
										
										$exp_1_to =  $exp_1_from_1[0];
										
										$exp_1_price = $exp_1_from_1[1];
										
										
										//pr($exp_1_to );
										//exit;
										if($weight>=$exp_1_from && $weight<=$exp_1_to)
											{
												$final_price = $exp_1_price; 
											}
									  }
									  return $final_price;
						  }
						  else
						  {
							  return '0';
						  }
			}
		
		function _getProductsUsingSpecifications($products="")
				{
					if(isset($products) and ($products))
					{
					    $x =0;
						foreach($products as $product)
							{
								$ratings = $this->__get_product_rating($product['Product']['wisn']);
								$products[$x]['Product']['rating'] = $ratings;
								$stock_detail = $this->_get_stock_position($product['Product']['stock']);
								$products[$x]['Product']['stock_detail']= $stock_detail; 
								if(isset($price) and ($price))
									{
											$MasterProduct = $this->__get_product_condition_price($price, $product['Product']['id']);
									}
								else
									{
										$MasterProduct = $this->__get_product_min_price($product['Product']['id']);
									}
								if(isset($MasterProduct) and ($MasterProduct))
									{
										$product_condition  = $this->_get_product_condition($MasterProduct['conditions']);
										$products[$x]['Product']['condition'] = $product_condition;
										$products[$x]['Product']['MasterProduct'] = $MasterProduct;
									}
								else
									{
										unset($products[$x]);
									}
								$x++;
							}
						return  $products;
					}

			}
		
		
			
		function _getProducts($conditions, $price="")
				{
					$this->paginate['Product'] =array('conditions' => $conditions.'',
														'limit' => 24,
														'fields' => array('Product.*') ,
														'order' => 'Product.created Desc'
														);
					$products = $this->paginate('Product');	
					if(isset($products) and ($products))
					{
					    $x =0;
						foreach($products as $product)
							{
								$ratings = $this->__get_product_rating($product['Product']['wisn']);
								$products[$x]['Product']['rating'] = $ratings;
								$stock_detail = $this->_get_stock_position($product['Product']['stock']);
								$products[$x]['Product']['stock_detail']= $stock_detail; 
								if(isset($price) and ($price))
									{
											$MasterProduct = $this->__get_product_condition_price($price, $product['Product']['id']);
									}
								else
									{
										$MasterProduct = $this->__get_product_min_price($product['Product']['id']);
									}
								if(isset($MasterProduct) and ($MasterProduct))
									{
										$product_condition  = $this->_get_product_condition($MasterProduct['conditions']);
										$products[$x]['Product']['condition'] = $product_condition;
										$products[$x]['Product']['MasterProduct'] = $MasterProduct;
									}
								else
									{
										unset($products[$x]);
									}
								$x++;
							}
						return  $products;
					}

			}
		function _getMerchantProduct($conditions, $merchant_id)
				{
					$this->paginate['Product'] =array('conditions' => $conditions.'',
														'limit' => 24, 
														'fields' => array('Product.*') ,
														'order' => 'Product.created Desc'
														);
					$products = $this->paginate('Product');	
					if(isset($products) and ($products))
					{
					    $x =0;
						foreach($products as $product)
							{
								$ratings = $this->__get_product_rating($product['Product']['wisn']);
								$products[$x]['Product']['rating'] = $ratings;
								$stock_detail = $this->_get_stock_position($product['Product']['stock']);
								$products[$x]['Product']['stock_detail']= $stock_detail; 
								$MasterProduct = $this->MasterProduct->find('all',
								 array('conditions'=>'MasterProduct.product_id='.$product['Product']['id'].'
								 and MasterProduct.seller_id="'.$merchant_id.'"'));
								 $MasterProduct = $MasterProduct[0]; 
								if(isset($MasterProduct) and ($MasterProduct))
									{
									}
								else
									{
										unset($products[$x]);
									}
								$x++;
							}
						return  $products;
					}

			}
			
		function _do_order_mail($customer_id="" , $seller_id="", $order_no ="")
		{
					
					$seller = $this->Seller->findById($seller_id);
					
					$this->data['Message']['hash'] = $this->__generateKey('Message');
					
					$get_subject = $this->MessageSubject->findById(1);  // 1 for Order confirmation
					
					$this->data['Message']['to_email'] = $seller['Seller']['merchant_token'].'@'.wondere_email_domain;
					
					
					$user_id = $this->User->findById($customer_id, array('fields'=>'User.*'));
					
					$seller_user_id = $this->User->findById($seller['Seller']['user_id'], array('fields'=>'User.*'));
					
					$this->data['Message']['subject_id'] = 1; 
					
					$this->data['Message']['to_user_id'] = $seller['Seller']['user_id']; //$user_id['User']['id'];
					
					$this->data['Message']['from_email'] =$seller['Seller']['merchant_token'].wondere_email_domain;
					
					$this->data['Message']['from_user_id'] =$customer_id; 
					
					$this->data['Message']['order_id'] =$order_no; 
					
					$this->data['Message']['dec'] = "
					
					Dear ".$seller_user_id['User']['name'].", 
					
					 Order Confirmation from ".$user_id['User']['name']." with
					 order no : ".$order_no." has been approved. Payment has been<br />
					 Paid to WonderE<br/>Thanks WonderE";
					
					$this->Message->save($this->data['Message']);
					
					$last_id = $this->Message->getLastInsertId();	
					
					$subject = 'Order confirmation Mail from Customer on WonderE Inc.'; 
					
					$this->Email->useremail($seller_user_id['User']['email'], $subject, 
					
					$this->data['Message']['dec']);
		}
		
	function _mail_to_customer($customer_id, $order_amount, $order_id)
		{
					
					$user_id = $this->User->findById($customer_id, array('fields'=>'User.*'));
					$subject = 'Order confirmation Mail from Customer on WonderE Inc.'; 
					$message = "
						Dear ".$user_id['User']['name'].", 
						Your Order Confirmation from WonderE Inc. of amount ".$order_amount." with
						order no : ".$order_id."
						<br> Thanks for order with us. We will deleiver Your order very soon. <br>
						Please check your login account to get complete detail of Paid Order.<br>
						Thanks <br>
						WonderE Inc.
					 ";
					$this->Email->useremail($user_id['User']['email'], $subject, $message);
		}
	function _mail_to_customer_for_shippment($data)
	{
		$customer_id = $this->Order->query('select orders.customer_id,orders.tracking_id,
		order_items.seller_id , order_items.product_id ,order_items.qty	 ,order_items.order_Item_Id 
		from orders left join order_items on (orders.id=order_items.order_id)
		 where  order_items.id="'.$data['OrderItem']['id'].'"');
		// pr($customer_id);
		 //exit;
		 if(isset($customer_id[0]) and ($customer_id[0]))
		 {
			$customer_id_user = $customer_id[0]['orders']['customer_id'];
			$website_url = Configure::read('Website.url');
			$seller = $this->Seller->findById($customer_id[0]['order_items']['seller_id']);
			$product = $this->_getProducts('Product.id='.$customer_id[0]['order_items']['product_id'].'');
			$product = $product[0]; 
			$order_item['Product'] = $product['Product'];
			$user_id = $this->User->findById($customer_id_user, array('fields'=>'User.*'));
			$subject = 'Shipping Confermation for Order-ID'.$customer_id[0]['orders']['tracking_id'].'On Wondere.com'; 
			$message = "
				Dear ".$user_id['User']['name'].", 
				Your Order shippment Confirmation from Merchant ".$seller['Seller']['bs_dis_name'].". with
				order no : ".$customer_id[0]['orders']['tracking_id']." on WonderE Inc. has been shipped.<br>
				Shipping Details :<br>
				shipping date: ".$data['OrderItem']['shipping_start_date']."<br>
				shipping delivery date: ".$data['OrderItem']['shipping_end_date']."<br>
				shipping Service Provider: ".$data['OrderItem']['shippingsps']."<br>
				shipping Tracking No: ".$data['OrderItem']['shipp_tracking']."<br>
				Merchant Memo: ".$data['OrderItem']['shipping_memo']."<br>
				
				Product : 
				<a href='".$website_url."products/product/".$product['Product']['slug']."' target='_blank'>".$product['Product']['name']."</a>
				<br>
				Quantity: ".$customer_id[0]['order_items']['qty']."<br>
				WSIN: ".$product['Product']['wisn']."<br>
				SKU: ".$product['Product']['MasterProduct']['sku']."<br>
				Order Item Id : ".$customer_id[0]['order_items']['order_Item_Id']."<br>
				Condition: ".$product['Product']['condition']['name']."<br><br>
								
				<a href='".$website_url."sellers/give_feedback/".$seller['Seller']['merchant_token']."' target='_blank'>Click on Link</a>
				to provide feedback for this seller.<br>
				Thanks<br>
				WonderE Inc.  
			 ";
				$this->Email->useremail($user_id['User']['email'], $subject, $message);
		 }
	}
	function _check_he_purchase_product($user_id, $product_id)
		{
			$order_user = $this->Order->query('select orders.id from orders left join order_items on (orders.id=order_items.order_id) where 
			orders.customer_id="'.$user_id.'" and order_items.product_id="'.$product_id.'" Limit 0, 1');
			if(isset($order_user['0']['orders']['id']) and ($order_user['0']['orders']['id']))
			{
				return 'Has been Purchased'; 
			}
			else
			{
				return 'Not Yet Purchase'; 
			}
		}
	function _get_product_price_conditions($product_id)
	{
		    $new_price_list         = $this->__new_price_offer_list($product_id);
            $used_price_list        = $this->__used_price_offer_list($product_id);
            $Collectible_price_list = $this->__Collectible_price_offer_list($product_id);
            $Refurbished_price_list = $this->__Refurbished_price_offer_list($product_id);
            $offer_list             = array();
            if (isset($new_price_list) and ($new_price_list))
            {
                $x = 0;
                foreach ($new_price_list as $new_price)
                {
                    $cond                                        = $this->_get_product_condition($new_price['MasterProduct']['conditions']);
                    $new_price_list[$x]['MasterProduct']['cond'] = $cond['name'];
                    $x++;
                }
                $offer_list[1]['name'] = 'new';
                $offer_list[1]['new']  = $new_price_list;
            }
            if (isset($used_price_list) and ($used_price_list))
            {
                $x1 = 0;
                foreach ($used_price_list as $used_price)
                {
                    $cond                                          = $this->_get_product_condition($used_price['MasterProduct']['conditions']);
                    $used_price_list[$x1]['MasterProduct']['cond'] = $cond['name'];
                    $x1++;
                }
                $offer_list[2]['name'] = 'Used';
                $offer_list[2]['Used'] = $used_price_list;
            }
            if (isset($Collectible_price_list) and ($Collectible_price_list))
            {
                $x11 = 0;
                foreach ($Collectible_price_list as $Collectible_price)
                {
                    $cond                                                  = $this->_get_product_condition($Collectible_price['MasterProduct']['conditions']);
                    $Collectible_price_list[$x11]['MasterProduct']['cond'] = $cond['name'];
                    $x11++;
                }
                $offer_list[3]['name']        = 'Collectible';
                $offer_list[3]['Collectible'] = $Collectible_price_list;
            }
            if (isset($Refurbished_price_list) and ($Refurbished_price_list))
            {
                $x111 = 0;
                foreach ($Refurbished_price_list as $Refurbished_price)
                {
                    $cond                                                   = $this->_get_product_condition($Refurbished_price['MasterProduct']['conditions']);
                    $Refurbished_price_list[$x111]['MasterProduct']['cond'] = $cond['name'];
                    $x111++;
                }
                $offer_list[4]['name']        = 'Refurbished';
                $offer_list[4]['Refurbished'] = $Refurbished_price_list;
            }
            return $offer_list; 
	}
			
	function _check_exist($model ="", $conditions="", $fields="", $limit="", $order="")
	{
		$check_exist = $this->$model->find('all',
												array(
														'conditions'=>$conditions,
														'fields' => $fields ,
														'limit' => $limit,
														'order'=>$order
											 ));
		if(isset($check_exist) and sizeof($check_exist) and (!empty($check_exist)))
			{
				return false;
			}
		else
			{
				return true;
			}
	}
	
	function _get_total_helpfull($product_review_id)
		{
			return $count_helpfull = $this->Helpfull->find('count', array('conditions'=>'Helpfull.product_review_id="'.$product_review_id.'"')); 
		}
	function _get_yes_helpfull($product_review_id)
		{
			return $count_helpfull = $this->Helpfull->find('count',
			 array('conditions'=>'Helpfull.product_review_id="'.$product_review_id.'" and Helpfull.helpfull=1')); 
		}
		
		
		/* make a URL small */
		function make_bitly_url($url)
		{
			$login="vineet07verma";
			$format = 'json';
			$version = '2.0.1'; 
			$appkey = "R_18fa27a9b6953fa9a00a8025c7fcdd88";
			  //create the URL
			  $bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$appkey.'&format='.$format;
			  
			  //get the url
			  //could also use cURL here
			  $response = file_get_contents($bitly);
			  
			  //parse depending on desired format
			  if(strtolower($format) == 'json')
				  {
					$json = @json_decode($response,true);
					return $json['results'][$url]['shortUrl'];
				  }
			  else //xml
				  {
					$xml = simplexml_load_string($response);
					return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
				  }
		}
		
		
		
		
}
